<!-- 库房管理-出库管理-销售退回收货单---新增操作 -->
<script lang="ts">
import { reactive, ref, watch, nextTick } from "vue";
import { ElForm } from "element-plus";
import { addSaleShippingBack } from "/@/api/wms/retreat";
import {
  querySaleShippingOrderItemById,
  querySaleShippingOrder
} from "/@/api/wms/deliver";
import { dateFormatYMD } from "/@/utils/date";
import { errorMessage, successMessage, alertMessage } from "/@/utils/message";
import { queryCodeNameByType } from "/@/api/log/interfaceLog";
import unitSelect from "/@/components/select/unit.vue"; //下拉选择供应商组件
export default {
  name: "addRetreat",
  components: {
    unitSelect
  },
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    }
  },
  setup(props, ctx) {
    // 添加
    const subItemData = reactive({
      loading: false,
      submitLoading: false,
      dialogShow: false,
      processData: [] as any[],
      bnoTypeData: [] as any[],
      listData: [] as any[],
      goodsData: [] as any[],
      storageData: [] as any[], //存储库房信息
      locationData: [] as any[], //存储库位信息
      numberData: [] as any[], //存储数量单位信息
      userInfo: {} as any,
      storageId: "" as any,
      formData: {
        arrivalTime: "",
        bnoNo: "",
        bnoType: "",
        createDate: "",
        customerName: "",
        customerCode: "",
        customerAddress: "",
        saleShippingBackItems: [],
        sourceCategory: "",
        sourceDocuments: "",
        storageLocation: ""
      },
      formRules: {
        outSourceNo: [
          { required: true, message: "请选择销售出货单", trigger: "blur" }
        ],
        bnoType: [
          { required: true, message: "请选择单据类型", trigger: "blur" }
        ],
        createDate: [
          { required: true, message: "请选择制单日期", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "请输入委外商", trigger: "blur" }
        ]
      }
    });

    watch(props, n => {
      console.log(props);
      subItemData.dialogShow = n.dialogShow;
      if (subItemData.dialogShow) {
        queryType("销售退回收货");
        subItemData.formData.createDate =
          dateFormatYMD(new Date()) + " 00:00:00";
      }
    });
    // 出库表单提交
    const insertForm = ref<InstanceType<typeof ElForm>>();
    const submitEvent = () => {
      insertForm.value.validate(valid => {
        if (valid) {
          var bool = false;
          var bool1 = false;
          if (subItemData.formData.saleShippingBackItems.length > 0) {
            for (
              var i = 0;
              i < subItemData.formData.saleShippingBackItems.length;
              i++
            ) {
              let data = subItemData.formData.saleShippingBackItems[i];
              Object.keys(data).forEach(key => {
                if (key == "materialName") {
                  data[key] == "" ? (bool = true) : null;
                }
                if (key == "reqNum") {
                  data[key] == 0 ? (bool1 = true) : null;
                }
              });
            }
            if (bool) {
              alertMessage("请将数据填写完整", "提示");
              return;
            }
            if (bool1) {
              alertMessage("数量不能为0", "提示");
              return;
            }
          } else {
            alertMessage("请填写详情信息", "提示");
            return;
          }
          subItemData.submitLoading = true;
          // 新增
          addSaleShippingBack(subItemData.formData)
            .then((res: any) => {
              if (res.code === 0) {
                subItemClose();
                ctx.emit("searchEvent");
                successMessage("新增成功");
              } else {
                subItemData.submitLoading = false;
                errorMessage(res.message);
              }
            })
            .catch(() => {
              errorMessage("操作失败");
              subItemData.submitLoading = false;
            });
        }
      });
    };

    const subItemClose = () => {
      nextTick(() => {
        subItemData.formData = {
          arrivalTime: "",
          bnoNo: "",
          bnoType: "",
          createDate: "",
          customerName: "",
          customerCode: "",
          customerAddress: "",
          saleShippingBackItems: [],
          sourceCategory: "",
          sourceDocuments: "",
          storageLocation: ""
        };
        subItemData.submitLoading = false;
        subItemData.dialogShow = false;
        insertForm.value.resetFields();
      });
      ctx.emit("addRetreatClose", false);
    };
    // 获取单据类型
    const queryType = (code: any) => {
      queryCodeNameByType(code).then((res: any) => {
        if (res.code == 0) {
          subItemData.bnoTypeData = res.data;
        }
      });
    };
    // 选择订单弹窗绑定数据
    const chooseOrder = reactive({
      dialogShow: false, //操作显示隐藏
      loading: false,
      detailData: [] as any[],
      orderId: 0,
      tableHeight: 0,
      totalCount: 0, //总数
      formData: {
        date: "" as any,
        bnoNo: "",
        bnoType: "",
        supplierName: "",
        finishFlag: "" as any,
        deliveryTime: "" as any,
        pageNum: 1, //页码
        pageRow: 15 //每页条数
      }
    });
    const chooseOrderShow = () => {
      chooseOrder.detailData = [];
      chooseOrder.dialogShow = true;
      nextTick(() => {
        chooseOrder.tableHeight =
          document.getElementById("orderForm").clientHeight + 40;
      });
      queryOrderSelect();
    };
    const queryOrderSelect = () => {
      chooseOrder.loading = true;
      const data: any = {};
      Object.assign(data, chooseOrder.formData);
      subItemData.loading = true;
      data.finishFlag =
        chooseOrder.formData.finishFlag === "" ||
        chooseOrder.formData.finishFlag == -1
          ? -1
          : chooseOrder.formData.finishFlag;

      if (chooseOrder.formData.date) {
        data.startMakeDate =
          dateFormatYMD(chooseOrder.formData.date[0]) + " 00:00:00";
        data.endMakeDate =
          dateFormatYMD(chooseOrder.formData.date[1]) + " 23:59:59";
      } else {
        data.startMakeDate = "";
        data.endMakeDate = "";
      }
      delete data.date;
      if (chooseOrder.formData.deliveryTime) {
        data.startDeliveryTime =
          dateFormatYMD(chooseOrder.formData.deliveryTime[0]) + " 00:00:00";
        data.endDeliveryTime =
          dateFormatYMD(chooseOrder.formData.deliveryTime[1]) + " 23:59:59";
      } else {
        data.startDeliveryTime = "";
        data.endDeliveryTime = "";
      }
      delete data.deliveryTime;
      querySaleShippingOrder(chooseOrder.formData).then((res: any) => {
        if (res.code == 0) {
          chooseOrder.detailData = res.data && res.data.list;
          chooseOrder.totalCount = res.data && res.data.total;
        }
        chooseOrder.loading = false;
      });
    };
    const chooseOrderClose = () => {
      chooseOrder.dialogShow = false;
      chooseOrder.detailData = [];
      chooseOrder.formData = {
        date: "" as any,
        bnoNo: "",
        bnoType: "",
        supplierName: "",
        finishFlag: "" as any,
        deliveryTime: "" as any,
        pageNum: 1, //页码
        pageRow: 15 //每页条数
      };
      chooseOrder.totalCount = 0; //总数
    };
    const handleSizeChange = val => {
      //改变每页数量
      chooseOrder.formData.pageRow = val;
      handleFilter(1);
    };
    const handleCurrentChange = val => {
      //改变页码
      handleFilter(val);
    };
    const handleFilter = val => {
      //查询事件
      chooseOrder.formData.pageNum = val;
      queryOrderSelect();
    };
    const handleSelectionChange = val => {
      console.log(val);
      if (val) {
        chooseOrder.orderId = val.id;
      }
    };
    // 删除
    const dele = i => {
      subItemData.formData.saleShippingBackItems.splice(i, 1);
    };
    // arrivalTime: "",
    //     bnoNo: "",
    //     bnoType: "",
    //     createDate: "",
    //     customerName: "",
    //     customerAddress: "",
    //     saleShippingBackItems: [],
    //     sourceCategory: "",
    //     sourceDocuments: "",
    //     storageLocation: ""
    // 点击确定
    const chooseOrderSure = () => {
      querySaleShippingOrderItemById(chooseOrder.orderId).then((res: any) => {
        if (res.code === 0) {
          subItemData.formData.sourceDocuments = res.data.bnoNo;
          // subItemData.formData.supplierCode = res.data.supplierCode;
          subItemData.formData.customerName = res.data.customerName;
          subItemData.formData.customerCode = res.data.customerCode;
          subItemData.formData.saleShippingBackItems =
            res.data.saleShippingOrderItems;
          for (var i in subItemData.formData.saleShippingBackItems) {
            subItemData.formData.saleShippingBackItems[i].pcsNum = 0;
            subItemData.formData.saleShippingBackItems[i].pcsUnit = "";
          }
        } else {
          errorMessage(res.message);
        }
      });

      chooseOrderClose();
    };
    // 双击选中
    const dobuleClick = val => {
      handleSelectionChange(val);
      chooseOrderSure();
    };
    return {
      subItemData,
      insertForm,
      submitEvent,
      subItemClose,
      chooseOrder,
      chooseOrderShow,
      queryOrderSelect,
      chooseOrderClose,
      handleSizeChange,
      handleCurrentChange,
      handleFilter,
      handleSelectionChange,
      chooseOrderSure,
      dobuleClick,
      dele
    };
  }
};
</script>
<template>
  <div>
    <!-- 表单弹框 -->
    <el-dialog
      v-model="subItemData.dialogShow"
      title="新增&保存"
      width="80%"
      top="7vh"
      :before-close="subItemClose"
      :close-on-click-modal="false"
    >
      <el-form
        ref="insertForm"
        :model="subItemData.formData"
        :rules="subItemData.formRules"
        label-align="right"
        label-width="100px"
      >
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item prop="sourceDocuments" label="销售出货单">
              <el-input
                v-model="subItemData.formData.sourceDocuments"
                placeholder="点击选择销售出货单"
                @click="chooseOrderShow"
                size="small"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item prop="bnoType" label="单据类型">
              <el-select
                v-model="subItemData.formData.bnoType"
                filterable
                clearable
                placeholder="请选择"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="item in subItemData.bnoTypeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item label="制单日期" prop="createDate">
              {{
                subItemData.formData.createDate
                  ? subItemData.formData.createDate.split(" ")[0]
                  : ""
              }}
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item label="退货客户" prop="customerName">
              <el-input
                v-model="subItemData.formData.customerName"
                size="small"
                style="width: 100%"
                placeholder="请输入退货客户"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item label="到货日期" prop="arrivalTime">
              <el-date-picker
                v-model="subItemData.formData.arrivalTime"
                value-format="YYYY-MM-DD"
                type="date"
                clearable
                style="width: 100%"
                placeholder="选择日期"
                size="small"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="客户位置">
              <el-input
                v-model="subItemData.formData.customerAddress"
                size="small"
                style="width: 100%"
                placeholder="请输入客户位置"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        stripe
        :data="subItemData.formData.saleShippingBackItems"
        border
        fit
        size="mini"
        highlight-current-row
        tooltip-effect="dark"
      >
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column
          prop="lineNo"
          label="行号"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="materialName"
          label="品名"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="materialCode"
          min-width="120"
          label="料号"
        ></el-table-column>
        <el-table-column prop="specification" label="规格" min-width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.specification"
              size="small"
              style="width: 100%"
              placeholder="请输入规格"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="saleNum"
          min-width="80"
          label="可退数量"
        ></el-table-column>
        <el-table-column prop="pcsNum" label="实退数量" width="140">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.pcsNum"
              :max="scope.row.saleNum"
              :min="0"
              size="small"
              style="width: 100%"
              placeholder="请输入"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="库存单位" width="110">
          <template #default="{ row }">
            <unit-select type="数量" v-model:value="row.pcsUnit" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="scope">
            <el-button type="danger" @click="dele(scope.$index)" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <vxe-button @click="subItemClose">取 消</vxe-button>
        <vxe-button status="primary" @click="submitEvent">确 定</vxe-button>
      </template>
    </el-dialog>
    <!-- 弹框选择销售出货单 -->
    <el-dialog
      v-model="chooseOrder.dialogShow"
      title="销售出货单"
      width="70%"
      top="9vh"
      :before-close="chooseOrderClose"
      :close-on-click-modal="false"
    >
      <el-form
        id="orderForm"
        ref="orderForm"
        :model="chooseOrder.formData"
        label-align="right"
        label-width="80px"
      >
        <el-row :gutter="10">
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="单号" prop="bnoNo">
              <el-input
                v-model="chooseOrder.formData.bnoNo"
                clearable
                @keyup.enter="queryOrderSelect"
                placeholder="请输入单号"
                size="small"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="供应商" prop="supplierName">
              <el-input
                v-model="chooseOrder.formData.supplierName"
                clearable
                @keyup.enter="queryOrderSelect"
                placeholder="请输入供应商"
                size="small"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="制单日期" prop="date">
              <el-date-picker
                v-model="chooseOrder.formData.date"
                size="small"
                style="width: 100%"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="queryOrderSelect"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="交期" prop="deliveryTime">
              <el-date-picker
                v-model="chooseOrder.formData.deliveryTime"
                size="small"
                style="width: 100%"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="queryOrderSelect"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label="状态" prop="finishFlag">
              <el-select
                v-model="chooseOrder.formData.finishFlag"
                filterable
                clearable
                placeholder="请选择状态"
                size="small"
                style="width: 100%"
              >
                <el-option label="完成" :value="1">完成</el-option>
                <el-option label="待办" :value="0">待办</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
            <el-form-item label-width="0px">
              <el-button type="primary" size="small" @click="queryOrderSelect"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        stripe
        v-loading="chooseOrder.loading"
        :data="chooseOrder.detailData"
        border
        fit
        :height="'calc(100% - ' + chooseOrder.tableHeight + 'px)'"
        size="mini"
        highlight-current-row
        tooltip-effect="dark"
        @row-dblclick="dobuleClick"
        @current-change="handleSelectionChange"
      >
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column
          prop="bnoNo"
          label="单号"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="bnoTypeName"
          label="单据类型"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="customerName"
          label="客户"
          min-width="220"
        ></el-table-column>
        <el-table-column
          prop="planBnoNo"
          label="出货计划单号"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="createUserCode"
          label="制单人"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="createDate" label="制单日期" width="100">
          <template #default="{ row }">
            {{ row.createDate ? row.createDate.split(" ")[0] : "" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag type="success" v-if="row.finishFlag == 1">完成</el-tag>
            <el-tag type="warning" v-if="row.finishFlag == 0">待办</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="chooseOrder.formData.pageNum"
        :page-sizes="[10, 15, 20, 30, 40, 50]"
        :page-size="chooseOrder.formData.pageRow"
        layout="total, sizes, prev, pager, next, jumper"
        :total="chooseOrder.totalCount"
      ></el-pagination>
      <template #footer>
        <el-button @click="chooseOrderClose" size="small">取 消</el-button>
        <el-button
          type="primary"
          size="small"
          v-if="chooseOrder.orderId"
          @click="chooseOrderSure"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
@import url("/@/style/dialog.css");
</style>
